package net.xxcl.exam.controller;

import net.xxcl.exam.pojo.*;
import net.xxcl.exam.service.MenuService;
import net.xxcl.exam.service.StudentService;
import net.xxcl.exam.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * User: 夏汛
 * Date: 11-12-1
 * Time: 上午11:46
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private StudentService studentService;

    /**
     * 登录验证
     * @param name
     * @param password
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/login",method= RequestMethod.POST)
    public String loginCheck(@RequestParam("name") String name, @RequestParam("password") String password,
                             @RequestParam("kaptcha") String kaptcha, HttpServletRequest request,HttpServletResponse response){
        try{
            String kaptchaExpected = (String)request.getSession()
                    .getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
            if (kaptcha == null || !kaptcha.equalsIgnoreCase(kaptchaExpected))
            {
                request.setAttribute("message","验证码错误");
                request.getSession().removeAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
                return "forward:/index.jsp";
            }
            if(request.getSession().getAttribute("student")!=null){
                request.getSession().removeAttribute("student");
            }
            if(request.getSession().getAttribute("user")!=null){
                request.getSession().removeAttribute("user");
            }
            Student student = studentService.login(name,password);
            if(student!=null){
                request.getSession().setAttribute("student",student);
                return "redirect:/student.jsp";
            } else {
                User user = userService.login(name,password);
                if(user!=null){
                    List<Integer> roles = userService.getRoleIdsByUserId(user.getId());
                    HttpSession session = request.getSession();
                    session.setAttribute("user",user);
                    session.setAttribute("roles",roles);
                    return "redirect:/user.jsp";
                }
            }
        } catch (Exception e){
            e.printStackTrace();
            return "forward:/index.jsp";
        }
        request.setAttribute("message","用户名或者密码错误！");
        return "forward:/index.jsp";
    }

    /**
     * 获取用户菜单
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value="/menus",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> getMenus(HttpServletRequest request,HttpServletResponse response){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        List<Integer> roles = (List<Integer>)request.getSession().getAttribute("roles");
        Object t = menuService.getMainMenuListByRoles(roles);
        responseMap.put("key",t);
        return responseMap;
    }

    /**
     * 获取用户列表
     * @param start
     * @param limit
     * @param name
     * @param username
     * @param deptids
     * @return
     */
    @RequestMapping(value = "/users",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> getKemus(@RequestParam("start") Integer start,
                                                     @RequestParam("limit") Integer limit,
                                                     @RequestParam(value = "name",required = false) String name,
                                                     @RequestParam(value = "username",required = false) String username,
                                                     @RequestParam(value = "deptids",required = false) String deptids){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        Criteria criteria = new Criteria();
        //加上查询条件
        if(!(name==null || name.equals(""))) criteria.put("blurredName","%"+name+"%");
        if(!(username==null || username.equals(""))) criteria.put("blurredUsername","%"+username+"%");
        if(!(deptids==null || deptids.equals(""))){
            String[] str = deptids.split(",");
            List<String> deptList = new ArrayList<String>();
            for(String s:str){
                deptList.add(s);
            }
            criteria.put("deptids",deptList);
        }
        int total = userService.countByExample(criteria);
        criteria.setMysqlOffset(start);
        criteria.setMysqlLength(limit);
        List<User> list = userService.selectByExample(criteria);
        for(User user:list){
            List<Role> roles = userService.getRolesByUserId(user.getId());
            String roleIds = "";
            String roleNames = "";
            for (Role role:roles){
                roleIds += role.getId()+",";
                roleNames += role.getName()+",";
            }
            if(roles.size()>0){
                user.setRoleIds(roleIds.substring(0,roleIds.length()-1));
                user.setRoleNames(roleNames.substring(0,roleNames.length()-1));
            }
        }
        responseMap.put("total",total);
        responseMap.put("rows",list);
        return responseMap;
    }

    /**
     * 新增或编辑
     * @param user
     * @return
     */
    @RequestMapping(value="/save",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> saveOrUpdate(@ModelAttribute("user") User user){
        Map<String,Object> responseMap = new HashMap<String,Object>();
        try{
            //新增部门
            if(user.getId()==null){
                user.setPassword("888888");
                userService.insert(user);
                responseMap.put("method", "Create");
                responseMap.put("success", "true");
                responseMap.put("info", "新增成功，初始密码为888888！");
            }
            //编辑部门
            else {
                userService.updateByPrimaryKeySelective(user);
                responseMap.put("success", "true");
                responseMap.put("info", "编辑成功！");
            }
        } catch (Exception e){
            e.printStackTrace();
            responseMap.put("info", e.getClass()+":"+e.getMessage());
        }
        return responseMap;
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @RequestMapping(value="/remove",method=RequestMethod.POST)
    public @ResponseBody Map<String,Object> remove(@RequestParam("ids") String ids){
        Map<String,Object> responseMap = new HashMap<String,Object>();
        try {
            userService.deleteUser(ids);
            responseMap.put("success", "true");
            responseMap.put("info", "删除成功！");
            return responseMap;
        }catch(Exception e) {
            e.printStackTrace();
            responseMap.put("info", e.getClass()+":"+e.getMessage());
            return responseMap;
        }
    }

    /**
     * 重置密码
     * @param ids
     * @return
     */
    @RequestMapping(value="/resetPass",method=RequestMethod.POST)
    public @ResponseBody Map<String,Object> resetPass(@RequestParam("ids") String ids){
        Map<String,Object> responseMap = new HashMap<String,Object>();
        try {
            userService.resetPass(ids,"888888");
            responseMap.put("success", "true");
            responseMap.put("info", "选中用户密码重置为888888！");
            return responseMap;
        }catch(Exception e) {
            e.printStackTrace();
            responseMap.put("info", e.getClass()+":"+e.getMessage());
            return responseMap;
        }
    }

    /**
     * 关联角色
     * @param roleids
     * @param userids
     * @return
     */
    @RequestMapping(value="/glRole",method=RequestMethod.POST)
    public @ResponseBody Map<String,Object> glRole(@RequestParam("roleids") String roleids,
                                                   @RequestParam("userids") String userids){
        Map<String,Object> responseMap = new HashMap<String,Object>();
        try {
            userService.glRole(roleids,userids);
            responseMap.put("success", "true");
            responseMap.put("info", "用户角色已修改成功");
            return responseMap;
        }catch(Exception e) {
            e.printStackTrace();
            responseMap.put("info", e.getClass()+":"+e.getMessage());
            return responseMap;
        }
    }
}
